<?php

class LyClient {
	
	private static $_instance;
	
	private function __construct() {
		$this->init();
	}
	
	private function __clone() {}
	
	protected function init() {
		include dirname(__FILE__).'/config.php';
	}
	
	public static function getInstance() {
		if(!self::$_instance) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}
	
	public function getSpaceUrl($uid) {
		return LY_HOME.'/url/tran?type=uc&mod=space&id='.$uid;
	}
	
	public function send($dataType, $method, $params = array(), $retArray = false) {
		
		$url = LY_API."/index?dataType={$dataType}&method={$method}";
		
		$queryString = $this->buildQueryString($params);
		
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 
		curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 120); 
		curl_setopt($ch, CURLOPT_POST, true); 

		curl_setopt($ch, CURLOPT_POST, count($params)); 
		curl_setopt($ch, CURLOPT_POSTFIELDS, $queryString); 
		
		$result = curl_exec($ch);
		curl_close($ch);
		return json_decode($result, $retArray);
	}
	
	protected function buildQueryString($data) {
		$queryString = '';
		foreach($data as $key => $value) { 
			if(strpos($value, 'http://') === 0) {
				$value = urlencode($value);
			}
			$queryString .= $key . '=' . $value . '&'; 
		} 
		$queryString = rtrim($queryString , '&');
		return $queryString;
	}
	
}

?>